/**
 * @file signal_out.c
 * @brief Functions used in the signal and the stderr output.
 * @version 1.0
 * @date Nov-2011
 * @author Leonardo Lino 2101101
 * @author Joaquim Ferreira 2101104
 */

#include <errno.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>

#include "signal_out.h"

/** @brief Function that treats the signal SIGINT.*/
void signal_routine (int signal)
{
  int aux;
  /**< @brief Holds the errno code.*/
  aux = errno;

  if (signal == SIGINT) {
    G_continue = 0;
    date_time ();
  }
  /**< @brief Restores the errno code.*/
  errno = aux;
}

/** @brief Function that send to the stderr some info.*/
void out_stderr (char *opt, time_t t_start)
{
  struct tm *time_end;
  time_t t_end;
  double t_dif;
  
  /**< @brief Get the ending time.*/
  time (&t_end);
  time_end = gmtime (&t_end);
  /**< @brief Get the diference of times, in miliseconds.*/
  t_dif = difftime (t_end, t_start) * 1000;


  fprintf (stderr, "\n# textTool\n");
  /**< @brief The input arguments. */
  fprintf (stderr, "# options: %s\n", opt);
  /**< @brief The number of processed files. */
  fprintf (stderr, "# files: %d\n", G_proc_files);
  /**< @brief The number of processed lines. */
  fprintf (stderr, "# lines: %d\n", G_proc_lines);
  /**< @brief Execution total in miliseconds. */
  fprintf (stderr, "# execution time: %.f miliseconds.\n", t_dif);
  fflush (stderr);
}

/** @brief Function that send to the stderr the date and the time.*/
void date_time (void)
{
  time_t rawtime;
  struct tm *timeinfo;
  char str_dt[50];
  
  time (&rawtime);
  timeinfo = localtime (&rawtime);
  strftime (str_dt, 50, "\nOperation interrupted by user @%Y-%m-%d %Hh%M\n", timeinfo);
  fprintf (stderr, "%s", str_dt);
}
